package com.gdk.ksoft.ui.reporters;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.assembly.dbhelper.FreporterDbHelper;
import com.gdk.ksoft.ui.reporters.adapters.OrderStatementAdapter;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * 订单日报查询页面
 */
public class AllOrderStatementActivity extends Activity {

    @ViewInject(R.id.pallOrderStatement_txtTitle)private TextView txtTile;//标题文字
    @ViewInject(R.id.pallOrderStatement_txtTotalMoney)private TextView txtTotalMoney;//总金额
    @ViewInject(R.id.pallOrderStatement_txtTotalPiece)private TextView txtTotalPiece;//总张数
    @ViewInject(R.id.pallOrderStatement_txtTotalCount)private TextView txtTotalCount;//总数量
    @ViewInject(R.id.pallOrderStatement_lstStatement)private ListView lstStatement;//订单日报列表
    @ViewInject(R.id.pallOrderStatement_txtNoUploadCount)private TextView txtNoUploadCount;//未上传数量


    private DbUtils dbUtils;//数据库操作对象
    private static final int PAGE_COUNT = 20;//每页最多显示20条
    private int pageCount = 0,currentPageIndex = 0;//当前页面总数及当前页数
    private List<HashMap<String,Object>> orderlist = new ArrayList<HashMap<String,Object>>();
    private List<HashMap<String,Object>> tmpOrderlist = new ArrayList<HashMap<String,Object>>();
    private OrderStatementAdapter orderStatementAdapter;//所有开单数据查询数据适配器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_order_statement);
        ViewUtils.inject(this);
        txtTile.setText("所有单据");
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        orderStatementAdapter = new OrderStatementAdapter(this,orderlist);
        lstStatement.setAdapter(orderStatementAdapter);
        lstStatement.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                int lastPos = view.getLastVisiblePosition();
                if(scrollState == SCROLL_STATE_IDLE && lastPos == view.getCount()-1){
                    int dataLen = tmpOrderlist.size();
                    currentPageIndex++;
                    if(currentPageIndex > pageCount - 1){
                        currentPageIndex = pageCount - 1;
                        return;
                    }
                    int backPageIndex = currentPageIndex + 1;
                    if(currentPageIndex == pageCount - 1){
                        orderlist.addAll(tmpOrderlist.subList(currentPageIndex*PAGE_COUNT,
                                dataLen%PAGE_COUNT==0?backPageIndex*PAGE_COUNT:
                                        currentPageIndex*PAGE_COUNT+dataLen%PAGE_COUNT));
                    }else{
                        orderlist.addAll(tmpOrderlist.subList(currentPageIndex*PAGE_COUNT,
                                backPageIndex*PAGE_COUNT));
                    }
                    orderStatementAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
        executeQueryTask();//执行查询任务
    }

    /**
     * 执行查询任务
     */
    public void executeQueryTask(){
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.add(Calendar.DAY_OF_MONTH,-SystemData.saleMan.cxddts);
        Calendar endCalendar = Calendar.getInstance(Locale.CHINA);
        int startYear = calendar.get(Calendar.YEAR);
        int startMonth = calendar.get(Calendar.MONTH)+1;
        int startDay = calendar.get(Calendar.DAY_OF_MONTH);
        int endYear = endCalendar.get(Calendar.YEAR);
        int endMonth = endCalendar.get(Calendar.MONTH)+1;
        int endDay = endCalendar.get(Calendar.DAY_OF_MONTH);
        String startDate = startYear+"-"+(startMonth>10?""+startMonth:"0"+startMonth)+"-"+(startDay>10?""+startDay:"0"+startDay);
        String endDate = endYear+"-"+(endMonth>10?""+endMonth:"0"+endMonth)+"-"+(endDay>10?""+endDay:"0"+endDay);
        requestOrdersInfo(AllOrderStatementActivity.this,startDate,endDate);//开始查询订单信息
    }


    /**
     * 查看未上传的
     * @param view
     */
    @OnClick(value={R.id.pallOrderStatement_txtNoUploadCount})
    public void onViewClick(View view){

    }

    /**
     * 列表项点击事件
     * @param av
     * @param view
     * @param position
     * @param itemId
     */
    @OnItemClick(value = {R.id.pallOrderStatement_lstStatement})
    public void onItemClick(AdapterView<?> av,View view,int position,long itemId){
        HashMap<String,Object> item = (HashMap<String,Object>)lstStatement.getItemAtPosition(position);
        Intent intent = new Intent(this,OrderStatementDetailActivity.class);
        intent.putExtra("orderNo",item.get("xdjh").toString());//写入单据号
        intent.putExtra("titleName","单据详情");
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
    }

    /**
     * 请求单据信息
     */
    public void requestOrdersInfo(final Context context,final String startDate,final String endDate){
        new AsyncTask<Void,Void,Void>(){
            private ProgressDialog dialog;
            private String errorMessage = null;
            private List<HashMap<String,Object>> statementlst = null;
            private HashMap<String,Object> totalInfo = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(AllOrderStatementActivity.this,"","加载中...");
            }
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    statementlst = FreporterDbHelper.findAllDataInfo(dbUtils, startDate, endDate);
                    totalInfo = FreporterDbHelper.findAllDateTotalInfo(dbUtils, startDate, endDate);
                }catch (Exception e){
                    errorMessage = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if (errorMessage != null) {
                    Toast.makeText(context, "查询出错了!原因：" + errorMessage, Toast.LENGTH_SHORT).show();
                    return;
                }
                if(statementlst == null || statementlst.size()<=0){
                    Toast.makeText(context, "当前没有任何开单数据!", Toast.LENGTH_SHORT).show();
                    return;
                }
                tmpOrderlist.clear();//清空原来的所有数据
                tmpOrderlist.addAll(statementlst);
                orderlist.clear();
                orderStatementAdapter.notifyDataSetChanged();
                int dataLen = statementlst.size();
                currentPageIndex = 0;//当前的页码
                pageCount = dataLen%PAGE_COUNT == 0?dataLen/PAGE_COUNT:dataLen/PAGE_COUNT+1;
                if(pageCount == 1){//如果只有一页的数据
                    orderlist.addAll(tmpOrderlist.subList(0,dataLen%PAGE_COUNT==0?PAGE_COUNT
                            :dataLen%PAGE_COUNT));
                }else{
                    orderlist.addAll(tmpOrderlist.subList(0,PAGE_COUNT));
                }
                orderStatementAdapter.notifyDataSetChanged();
                lstStatement.setSelection(0);//默认选中第一项
                if(totalInfo!=null){//显示统计信息
                    txtNoUploadCount.setText(totalInfo.get("noupload").toString());
                    txtTotalCount.setText(totalInfo.get("totalXCount").toString());
                    txtTotalMoney.setText(FormatUtils.exactNumber(totalInfo.get("totalMoney"),"0.00")+"元");
                    txtTotalPiece.setText(totalInfo.get("totalCount").toString()+"张");
                }
            }
        }.execute();
    }

    @OnClick(value={R.id.pallOrderStatement_imgBack})
    public void onBackClick(View view){
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
